﻿Imports System.Net.Sockets
Imports System.IO
Imports System.Threading
Imports System.Text
Imports System.Net
Imports System.Web.Script.Serialization
Imports Mqtt客户端
'Imports HslCommunication.MQTT

Public Class Form1
    Dim WithEvents mClient As MqttClient
    Dim showSenior As Boolean = True
    Dim showWill As Boolean = True
    Dim isLoad As Boolean = False
    Dim jsonArray As JSONArray = New JSONArray
    'Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    '    textClientId.Text = MqttClient.getCpuGuid
    '    Dim onnectOptions As New MqttConnectOptions()
    '    onnectOptions.setMqttVersion(MqttConnectOptions.Version.MQTT_VERSION_5_0)
    '    onnectOptions.userName = textUser.Text
    '    onnectOptions.password = textPwd.Text
    '    onnectOptions.keepAliveInterval = Val(textKeepLive.Text)
    '    onnectOptions.cleanSession = True
    '    onnectOptions.setProperies(60, 500, , 50)
    '    'onnectOptions.willTopic = "最后的话题"
    '    'onnectOptions.willMessage = New MqttMessage()
    '    'onnectOptions.willMessage.QoS = 1
    '    onnectOptions.setWill("Off line", "It's off the line", 2, False, 0, 0, "test", MqttProperties.MqttPayloadFormat.UNSPECIFIED_BYTES)
    '    ' onnectOptions.willMessage.setPayload("保留最后的消息")
    '    mClient = New MqttClient(Me, onnectOptions)

    '    Dim bit As Byte = mClient.getBitVal(7564334564676534549, 44)

    'End Sub
    'Private Sub btnConnect_Click(sender As Object, e As EventArgs)
    '    If mClient.mqttConnect(ComboAddr.Text, Val(textPort.Text), textClientId.Text) Then
    '        btnConnect.Enabled = False
    '        btnDisconnect.Enabled = True
    '    End If
    'End Sub

    'Private Sub btnDisconnect_Click(sender As Object, e As EventArgs)
    '    If mClient.mqttDisconnect() <> 0 Then
    '        ' btnConnect.Enabled = True
    '        ' btnDisconnect.Enabled = False
    '    End If
    'End Sub
    'Private Sub Button1_Click(sender As Object, e As EventArgs)
    '    Dim properties As New MqttProperties()
    '    properties.setProperies(30, "关闭灯光", MqttProperties.MqttPayloadFormat.UTF_8, 30)
    '    properties.setSubscriptionIdentifier(4534)  '设置订阅标识符
    '    mClient.publish("关灯", "灯已关闭", False, 2, False, properties) ' {&H32, &H7, &H0, &H3, &H61, &H2F, &H62, &H0, &HA} ' getPublishData("a/b", "灯已开启", 10)
    '    'clientSocket.Send(pData)

    'End Sub

    'Private Sub Button2_Click(sender As Object, e As EventArgs)
    '    Dim p As New MqttProperties()
    '    p.setSubscriptionIdentifier(4534)  '设置订阅标识符
    '    p.setUserProperty("admin")
    '    Dim subOpts(2) As MqttSubscriptionOptions
    '    subOpts(0) = New MqttSubscriptionOptions()
    '    subOpts(1) = New MqttSubscriptionOptions()
    '    subOpts(2) = New MqttSubscriptionOptions()
    '    subOpts(0).QoS = MqttClient.MqttQoS.QoS_1
    '    subOpts(0).setNoLocal(False)
    '    subOpts(1).QoS = MqttClient.MqttQoS.QoS_2
    '    subOpts(1).setNoLocal(False)
    '    subOpts(2).QoS = MqttClient.MqttQoS.QoS_1
    '    subOpts(2).setNoLocal(False)

    '    mClient.subscribe({"开灯", "关灯", "亮度"}, subOpts, , p)
    'End Sub
    'Private Sub Button3_Click(sender As Object, e As EventArgs)
    '    mClient.unSubscribe({"开灯", "关灯"})
    'End Sub

    'Private Sub mClient_disConnectSuccess(isMqttConnect As Boolean) Handles mClient.disConnectSuccess
    '    btnConnect.Enabled = True
    '    btnDisconnect.Enabled = False
    'End Sub
    'Private Sub mClient_publishReceiveArrival(topic As String, message As MqttMessage) Handles mClient.publishReceiveArrival
    '    TextBox1.Text = "主题:" + topic + " 主题消息:" + message.getPayloadString
    'End Sub


    Private Sub Panel7_Resize(sender As Object, e As EventArgs) Handles Panel7.Resize
        Panel1.Left = 10
        Panel1.Top = Label2.Bottom + 5
        Panel1.Height = 215
        Panel3.Left = 10
        Panel3.Top = Label3.Bottom + 5
        Panel6.Left = 10
        Panel6.Top = Label15.Bottom + 5
        Dim right As Integer = IIf(Panel7.VerticalScroll.Visible, 35, 20)
        Panel1.Width = Panel7.Width - right
        Panel3.Width = Panel7.Width - right
        Panel6.Width = Panel7.Width - right
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load

        isLoad = True
        ComboBox1.SelectedIndex = 0
        ComboBox2.SelectedIndex = 2
        Label2.Top = 10
        Label2.Left = 10
        Panel1.SetBounds(10, Label2.Bottom + 5, Panel7.Width - 20, 215)
        Label3.Top = Panel1.Bottom + 10
        Label3.Left = 10
        PictureBox1.Top = Label3.Top
        PictureBox1.Left = Label3.Right
        Panel3.SetBounds(10, Label3.Bottom + 5, Panel7.Width - 20, IIf(ComboBox2.Text.Equals("5.0"), 323, 210))
        Label15.Top = Panel3.Bottom + 10
        Label15.Left = 10
        PictureBox2.Top = Label15.Top
        PictureBox2.Left = Label15.Right
        Panel6.SetBounds(10, Label15.Bottom + 5, Panel7.Width - 20, IIf(ComboBox2.Text.Equals("5.0"), 449, 251))


        Dim intBuff() As Integer = New Integer() {&H23, &H75, &H12, &H89, &H45, &H9, &H11, &H56, &H77, &H21, &H43}
        InsertSort(intBuff)

        ' Dim strBuff As String = TextBox7.Text
        ' Dim list() As String = strBuff.Split(vbCrLf)
        '  For i = 0 To list.LongCount - 1
        '  list(i) = list(i).Replace(vbLf, "")
        '  Dim subList() As String = list(i).Split(vbTab)
        'Dim provinceJson As JSONObject '= New JSONObject
        'Dim cityJson As JSONObject, countyJson As JSONObject
        'Dim countyArray As JSONArray, cityArray As JSONArray
        'If jsonArray.Count > 0 Then
        '    For j = 0 To jsonArray.Count - 1
        '        If jsonArray.OptJSONObject(j).optString("province", "") = subList(0) Then
        '            provinceJson = jsonArray.GetJSONObject(j)
        '            Exit For
        '        End If
        '    Next
        '    If provinceJson IsNot Nothing Then
        '        cityArray = provinceJson.optJSONArray("cityInfo")
        '        If cityArray IsNot Nothing AndAlso cityArray.Count > 0 Then
        '            For j = 0 To cityArray.Count - 1
        '                If cityArray.OptJSONObject(j).optString("city", "") = subList(1) Then
        '                    cityJson = cityArray.OptJSONObject(j)
        '                End If
        '            Next
        '        Else
        '        End If
        '    Else
        '        provinceJson = New JSONObject
        '        cityJson = New JSONObject
        '        countyJson = New JSONObject
        '        countyArray = New JSONArray
        '        cityArray = New JSONArray
        '        '--------------写入县、区信息-------------------
        '        countyJson.put("county", subList(2))
        '        Dim countyId As String = subList(3).Substring(1, 6)
        '        countyJson.put("countyId", countyId)
        '        countyJson.put("weatherCode", subList(3))
        '        countyJson.put("latitude", subList(4))
        '        countyJson.put("longitude", subList(5))
        '        countyJson.put("adcode", IIf(subList.LongCount > 5, subList(6), ""))
        '        countyArray.Put(countyJson)   '将县、区信息添加到县区数组
        '        '-------------写入市、地区信息-------------
        '        cityJson.put("city", subList(1))
        '        Dim cityId As String = subList(3).Substring(1, 4)
        '        cityJson.put("cityId", cityId)
        '        cityJson.put("countyInfo", countyArray)  '将县、区数组写入
        '        cityArray.Put(cityJson)
        '        '--------------写入省信息-----------------
        '        provinceJson.put("province", subList(0))
        '        Dim provinceId As String = subList(3).Substring(1, 2)
        '        provinceJson.put("provinceId", provinceId)
        '        provinceJson.put("cityInfo", cityArray)   '将市、地区写入
        '        jsonArray.Put(provinceJson)   '将省添加到数组
        '    End If
        'Else
        '    provinceJson = New JSONObject
        '    provinceJson.put("province", subList(0))
        '    Dim provinceId As String = subList(3).Substring(1, 2)
        '    provinceJson.put("provinceId", provinceId)
        '    countyJson = createCountyInfo(subList)
        '    cityJson = createCityInfo(subList)
        '    setCountyInfo(cityJson, countyJson)
        '    setCityInfo(provinceJson, cityJson)
        '    jsonArray.Put(provinceJson)   '将省添加到数组
        'End If
        ' putProvince(jsonArray, subList)
        ' Next
        'For i = 0 To jsonArray.Count - 1
        '    Dim jsonObj As JSONObject = jsonArray.GetJSONObject(i)
        '    Dim id As String = IIf(i + 1 < 10, "0" & (i + 1), (i + 1))
        '    jsonObj.put("provinceId", id)
        '    Dim cityArray As JSONArray = jsonObj.optJSONArray("cityInfo")
        '    If cityArray IsNot Nothing Then
        '        For j = 0 To cityArray.Count - 1
        '            Dim cityId As String = id & IIf(j + 1 < 10, "0" & (j + 1), (j + 1))
        '            Dim citry As JSONObject = cityArray.GetJSONObject(j)
        '            citry.put("cityId", cityId)
        '        Next
        '    End If
        'Next
        'Clipboard.SetDataObject(jsonArray.toString)
        'TextBox8.Text = jsonArray.toString 'jsonArray.toString()
        mClient = New MqttClient()
        'Dim mProperties As New MqttProperties()
        'mProperties.addUserProperty("test", "cs1")
        'mProperties.addUserProperty("user", "vbff")
        'Dim buf() As Byte = mProperties.getUserPropertyByte

    End Sub
    Private Sub putProvince(ByRef jArray As JSONArray, dataLast() As String)
        Dim provinceJson As JSONObject = Nothing
        Dim pName As String = dataLast(0)
        If jArray IsNot Nothing AndAlso jArray.Count > 0 Then
            Dim repeat As Boolean
            For i = 0 To jArray.Count - 1
                Dim province As String = jArray.GetJSONObject(i).optString("province", "")
                If province = pName Then
                    provinceJson = jArray.GetJSONObject(i)
                    repeat = True
                    Exit For
                End If
            Next
            If repeat = False Then
                provinceJson = New JSONObject
                provinceJson.put("province", pName)
                Dim countyJson As JSONObject = createCountyInfo(dataLast)
                Dim cityJson As JSONObject = createCityInfo(dataLast)
                setCityInfo(provinceJson, cityJson)
                setCountyInfo(cityJson, countyJson)
                jArray.Put(provinceJson)   '将省添加到数组
            Else    '已经存在该省信息
                Dim countyJson As JSONObject = createCountyInfo(dataLast)  '创建县、辖区信息
                Dim cityJson As JSONObject = createCityInfo(dataLast)  '创建市、地区信息
                setCityInfo(provinceJson, cityJson)
                setCountyInfo(cityJson, countyJson)   '将县信息写入市市信息
                'jArray.Put(provinceJson)   '将省添加到数组
            End If
        Else
            jArray = New JSONArray
            provinceJson = New JSONObject
            provinceJson.put("province", pName)
            Dim countyJson As JSONObject = createCountyInfo(dataLast)
            Dim cityJson As JSONObject = createCityInfo(dataLast)
            setCityInfo(provinceJson, cityJson)
            setCountyInfo(cityJson, countyJson)

            jArray.Put(provinceJson)   '将省添加到数组
        End If
    End Sub
    Private Sub setCityInfo(provinceJson As JSONObject, ByRef cityInfo As JSONObject)
        Dim cityInfoArray As JSONArray = Nothing
        If provinceJson IsNot Nothing Then
            If cityInfo IsNot Nothing Then
                cityInfoArray = provinceJson.optJSONArray("cityInfo")
                Dim repeat As Boolean
                If cityInfoArray IsNot Nothing Then
                    For i = 0 To cityInfoArray.Count - 1
                        If cityInfoArray.OptJSONObject(i).optString("city", "") = cityInfo.optString("city", "") Then
                            cityInfo = cityInfoArray.OptJSONObject(i)
                            repeat = True
                            Exit For
                        End If
                    Next
                    If repeat = False Then
                        cityInfoArray.Put(cityInfo)
                    End If
                Else
                    cityInfoArray = New JSONArray
                    cityInfoArray.Put(cityInfo)
                    provinceJson.put("cityInfo", cityInfoArray)
                End If

            End If
        End If
    End Sub
    Private Function createCityInfo(dataLast() As String) As JSONObject
        Dim cityInfo As JSONObject = New JSONObject
        cityInfo.put("city", dataLast(1))
        Return cityInfo
    End Function
    ''' <summary>
    ''' 设置县，辖区信息
    ''' </summary>
    ''' <param name="cityInfo"></param> 市、地区信息
    ''' <param name="countyInfo"></param> 县、辖区对象
    Private Sub setCountyInfo(cityInfo As JSONObject, countyInfo As JSONObject)
        Dim countyInfoArray As JSONArray = Nothing
        If cityInfo IsNot Nothing Then
            If countyInfo IsNot Nothing Then
                countyInfoArray = cityInfo.optJSONArray("countyInfo")

                Dim repeat As Boolean
                If countyInfoArray IsNot Nothing Then
                    For i = 0 To countyInfoArray.Count - 1
                        If countyInfoArray.OptJSONObject(i).optString("weatherCode", "") = countyInfo.optString("weatherCode", "") Then
                            repeat = True
                            Exit For
                        End If
                    Next
                    If repeat = False Then
                        countyInfoArray.Put(countyInfo)
                    End If
                Else
                    countyInfoArray = New JSONArray
                    countyInfoArray.Put(countyInfo)
                    cityInfo.put("countyInfo", countyInfoArray)
                End If
            End If
        End If
    End Sub
    ''' <summary>
    ''' 创建县、辖区JSON对象
    ''' </summary>
    ''' <param name="dataLast"></param>
    ''' <returns></returns>
    Private Function createCountyInfo(dataLast() As String) As JSONObject
        Dim countyJson = New JSONObject
        '--------------写入县、区信息-------------------
        countyJson.put("county", dataLast(2))
        ' Dim countyId As String = dataLast(3).Substring(1, 6)
        'countyJson.put("countyId", countyId)
        countyJson.put("weatherCode", dataLast(3))
        countyJson.put("latitude", CType(dataLast(4), Double))
        countyJson.put("longitude", CType(dataLast(5), Double))
        If dataLast.Length > 6 AndAlso dataLast(6) <> "" Then
            countyJson.put("adcode", CInt(dataLast(6)))
        Else
            countyJson.put("adcode", 0)
        End If
        Return countyJson
    End Function

    Private Function createJsonString(ByVal name As String, ByVal val As Object) As String
        Dim jsonObj As JSONObject = New JSONObject()
        jsonObj.put(name, val)
        Return jsonObj.toString()
    End Function

    Private Sub Panel1_Resize(sender As Object, e As EventArgs) Handles Panel1.Resize
        TextName.Width = Panel1.Width - TextName.Left - 30
        TextClientId.Width = TextName.Width
        ComboAddr.Width = Panel1.Width - ComboAddr.Left - NumericPort.Width - 35
        NumericPort.Left = ComboAddr.Left + ComboAddr.Width + 5
        TextBox6.Width = TextName.Width
        TextBox5.Width = TextName.Width
    End Sub
    Private Sub Panel3_Resize(sender As Object, e As EventArgs) Handles Panel3.Resize
        NumericUpDown2.Width = Panel3.Width - NumericUpDown2.Left - 30
        NumericUpDown3.Width = NumericUpDown2.Width
        ComboBox2.Width = NumericUpDown2.Width
        NumericUpDown4.Width = NumericUpDown2.Width
        NumericUpDown5.Width = NumericUpDown2.Width
        NumericUpDown6.Width = NumericUpDown2.Width
    End Sub

    Private Sub Panel6_Resize(sender As Object, e As EventArgs) Handles Panel6.Resize
        TextBox1.Width = Panel6.Width - TextBox1.Left - 30
        TextBox7.Width = TextBox1.Width
        NumericUpDown7.Width = TextBox1.Width
        NumericUpDown8.Width = TextBox1.Width
        TextBox8.Width = TextBox1.Width
    End Sub

    Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
        If Not showSenior Then
            If ComboBox2.Text.Equals("5.0") Then
                Panel3.Height = 323
            Else
                Panel3.Height = 210
            End If
            showSenior = True
            PictureBox1.Image = Mqtt客户端.My.Resources.Resources.up
        Else
            Panel3.Height = 0
            showSenior = False
            PictureBox1.Image = Mqtt客户端.My.Resources.Resources.down
        End If
        Label15.Top = Panel3.Bottom + 10
        PictureBox2.Top = Label15.Top
        Panel6.Top = Label15.Bottom + 5
    End Sub

    Private Sub PictureBox2_Click(sender As Object, e As EventArgs) Handles PictureBox2.Click
        If Not showWill Then
            If ComboBox2.Text.Equals("5.0") Then
                Panel6.Height = 449
            Else
                Panel6.Height = 251
            End If
            showWill = True
            PictureBox2.Image = Mqtt客户端.My.Resources.Resources.up
        Else
            Panel6.Height = 0
            showWill = False
            PictureBox2.Image = Mqtt客户端.My.Resources.Resources.down
        End If
    End Sub

    Private Sub ComboBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox2.SelectedIndexChanged
        If Not isLoad Then
            If ComboBox2.Text.Equals("5.0") Then
                If showSenior Then
                    Panel3.Height = 323
                End If
                If showWill Then
                    Panel6.Height = 449
                End If
            Else
                If showSenior Then
                    Panel3.Height = 210
                End If
                If showWill Then
                    Panel6.Height = 251
                End If
            End If
            Label15.Top = Panel3.Bottom + 10
            PictureBox2.Top = Label15.Top
            Panel6.Top = Label15.Bottom + 5
        End If
        isLoad = False
    End Sub
    ''' <summary>
    ''' 冒泡排序
    ''' </summary>
    ''' <param name="arrayBuff"></param>
    ''' <remarks></remarks>
    Private Sub BubbleSort(arrayBuff() As Integer)
        Dim temp As Integer = 0
        Dim swapped As Boolean = False  '数据交换标志
        For i As Integer = 0 To arrayBuff.Length - 1
            swapped = False
            For j As Integer = 0 To arrayBuff.Length - 2 - i
                If arrayBuff(j) > arrayBuff(j + 1) Then   '判断是否需要交换
                    '交换两个数据
                    temp = arrayBuff(j)
                    arrayBuff(j) = arrayBuff(j + 1)
                    arrayBuff(j + 1) = temp
                    swapped = True
                End If
            Next
            If swapped = False Then
                Return
            End If
        Next
    End Sub
    ''' <summary>
    ''' 插入排序。算法步骤：
    ''' 将第一待排序序列第一个元素看做一个有序序列，把第二个元素到最后一个元素当成是未排序序列。
    ''' 从头到尾依次扫描未排序序列，将扫描到的每个元素插入有序序列的适当位置。
    ''' （如果待插入的元素与有序序列中的某个元素相等，则将待插入元素插入到相等元素的后面。）
    ''' </summary>
    ''' <param name="arrayBuff"></param>
    ''' <remarks></remarks>
    Private Sub InsertSort(arrayBuff() As Integer)
        For i As Integer = 1 To arrayBuff.Length - 1
            Dim temp As Integer = arrayBuff(i)
            For j As Integer = i - 1 To 0 Step -1
                If arrayBuff(j) > temp Then
                    arrayBuff(j + 1) = arrayBuff(j)
                    arrayBuff(j) = temp
                Else
                    Exit For
                End If
            Next
        Next
    End Sub

    Private Sub MqttMsgText1_Load(sender As Object, e As EventArgs)

    End Sub

    Private Sub Panel1_Paint(sender As Object, e As PaintEventArgs) Handles Panel1.Paint

    End Sub

    Private Sub Panel7_QueryAccessibilityHelp(sender As Object, e As QueryAccessibilityHelpEventArgs) Handles Panel7.QueryAccessibilityHelp

    End Sub

    Private Sub ComboAddr_TextChanged(sender As Object, e As EventArgs) Handles ComboAddr.TextChanged
        NumericPort.Enabled = True
        For Each addr As String In ComboAddr.Items
            If addr.ToLower.Equals(ComboAddr.Text.ToLower) Then
                NumericPort.Value = 1883
                NumericPort.Enabled = False
                Exit For
            End If
        Next
    End Sub

    Private Sub Label28_Click(sender As Object, e As EventArgs) Handles Label28.Click
        If mClient.Connected Then
            mClient.ConnectClose()
        Else
            mClient.ConnectServer(ComboAddr.Text, NumericPort.Value)
        End If
    End Sub

    Private Sub mClient_disConnectSuccess(onlyMqttConnect As Boolean) Handles mClient.disConnectSuccess
        Label28.Text = "连接"
    End Sub

    Private Sub mClient_connectMqttSuccess(sessionPresent As Boolean) Handles mClient.connectMqttSuccess
        Label28.Text = "断开"
        mClient.subscribe("他依然", MqttClient.MqttQoS.QoS_0)
        'mClient.publish()
    End Sub


    Private Sub mClient_publishTopicProcess(controlType As MqttClient.ControlType, Identifier As UShort) Handles mClient.publishTopicProcess

    End Sub

    Private Sub mClient_publishReceiveArrival(topic As String, message As MqttMessage) Handles mClient.publishReceiveArrival
        MsgBox(message.getPayloadString)
    End Sub

    Private Sub ComboAddr_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboAddr.SelectedIndexChanged

    End Sub
End Class
